<template>
  <div>
    <el-form ref="form" :inline="true" :model="form">
      <el-form-item label="选择回访问卷" class="form-group" prop="questionnaireType">
        <el-select v-model="form.questionnaireType" placeholder="请选择" :disabled="this.btnDisable" @change="getQuestionTable">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">开始答题</el-button>
      </el-form-item>
    </el-form>

    <FilterTable
      ref="table"
      :fetchapi="fetchApi"
      :columns="columns"
      :params="fetchParams"
      :datakey="'rows'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="columns => (this.selectColumns = columns)"
      :height="230"
      :onSyncTableData="getQuestionAll"
    ></FilterTable>

    <!-- 问卷录入 -->
    <BaseDialog ref="tablesingleCopy" :visible.sync="question" title="问卷信息录入" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <questionnaireModify :selColumn="this.selectColumns" @saveQuestions="saveQuestions" @closeQuestionModify="closeQuestionModify" />
    </BaseDialog>

    <BaseDialog :visible.sync="showQuestionDialog" title="问卷信息录入" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto' }">
      <el-form ref="form1" :model="form1" inline>
        <el-row v-for="(item, index) in currentQuestionList" :key="index" style="marginBottom:10px;lineHeight:1.2">
          <p style="padding:10px 0">{{ item.questionContent }}</p>
          <el-col :span="8"
            ><el-form-item label="答案">
              <el-select
                v-if="item.questionType === 'SELECT' || item.questionType === 80741002 || item.questionType === 80741003"
                v-model="form1.answers[index].answer"
                placeholder="请选择"
                :multiple="item.questionType === 'MULTIPLE_SELECT' || item.questionType === 80741003"
              >
                <el-option v-for="answer in item.answerList" :key="answer.answer" :label="answer.answer" :value="answer.answer"></el-option>
              </el-select>
              <el-input v-if="item.questionType === 'INPUT' || item.questionType === 80741001" v-model="form1.answers[index].answer"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8"
            ><el-form-item label="备注">
              <el-input v-model="form1.answers[index].remark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="onSaveAllAnswert">确定</el-button>
        </el-form-item>
      </el-form>
    </BaseDialog>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import { notifyAction } from '@/utils/index';

import { getQuestionnaireInfos, questionPag, questionAndAnswer } from '@/api/customerRepair/visitRules/questionnaireMake2';
import questionnaireModify from '@/pages/customerRepair/customerCare/maintenanceRemind/questionnaireModify';

export default {
  components: {
    questionnaireModify
  },
  mixins: [dictionary],
  props: ['rData', 'remindSource'],
  data() {
    return {
      fetchApi: questionPag,
      columns: this.createdTable(),
      fetchParams: { xhrAbort: true },
      options: [],
      value: '',
      questionList: [],
      selectColumns: {},
      showQuestionDialog: false,
      question: false,
      indexId: '',
      btnDisable: false,
      questionId: null,
      currentQuestionList: [],
      form: {
        questionnaireType: ''
      },
      form1: {
        answers: []
      },
      rules: {
        questionnaireType: [{ required: true, message: '请选择问卷', trigger: 'blur' }]
      }
    };
  },
  created() {
    this.queryQuestionnaireInfo(); // // 获取问卷类型
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  methods: {
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          fixed: 'left',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 70,
          fixed: 'left',
          disabled: this.btnDisable,
          render: props => {
            return (
              <el-button type="text" size="mini" disabled={this.btnDisable} title="编辑" onClick={() => this.openQuestion(props.row)}>
                编辑
              </el-button>
            );
          }
        },
        {
          title: '问卷名称',
          dataIndex: 'questionnaireCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '问题名称',
          dataIndex: 'questionCode',
          sorter: true,
          filter: true,
          hidden: true,
          filterType: 'input'
        },
        {
          title: '问题内容',
          dataIndex: 'questionContent',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '类型',
          dataIndex: 'questionType',
          sorter: true,
          filter: true,
          filterType: 'input',
          // filterItems: this.createDictList('8074'),
          render: props => {
            return <div>{this.createDictText(props.row.questionType, '8074')}</div>;
          }
        },
        {
          title: '必填',
          dataIndex: 'isMustFilled',
          sorter: true,
          filter: true,
          filterType: 'input',
          // filterItems: this.createDictList('1004'),
          render: props => {
            return <span>{this.createDictText(props.row.isMustFilled, '1004')}</span>;
          }
        },
        {
          title: '答案',
          dataIndex: 'answer',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          editType: 'input',
          editItems: []
        },
        {
          title: '备注',
          dataIndex: 'remark',
          sorter: true,
          filter: true,
          filterType: 'input'
          // editable: true,
          // editType: 'input'
        }
      ];
    },

    onSubmit() {
      // this.$refs.form.validate(valid => {
      //   if (valid) {
      //     debugger
      //     this.showQuestionDialog = true;
      //     alert('submit!');
      //   } else {
      //     console.log('error submit!!');
      //     this.$notify()
      //     return false;
      //   }
      // });
      if(this.form.questionnaireType) {
        this.showQuestionDialog = true;
      }else {
        notifyAction("请先选择问卷再答题！")
      }
    },

    onSaveAllAnswert() {
      //
      this.showQuestionDialog = false;
      this.questionList.forEach(x => {
        let item = this.form1.answers.find(value => {
          return value.questionId === x.questionId;
        });
        x.answer = item.answer || '';
        x.remark = item.remark || '';
      });
    },

    // 获取问卷类型
    async queryQuestionnaireInfo() {
      let obj = {
        // 回访问卷查询传递代码
        questionnaireType: this.rData.questionnaireType
      };
      const res = await getQuestionnaireInfos(obj); // 查询问卷（不查模板）
      this.options = res.data.map(x => ({ value: x.questionnaireId, label: x.questionnaireName, index: x.index, disabled: false }));
      this.options = [...this.options];
    },

    // 获取问卷表格数据
    async getQuestionTable(val) {
      let obj = {
        questionnaireId: val
      };
      this.fetchParams = Object.assign({}, obj, { xhrAbort: false });

      // 获取所有的问题和答案
      const res = await questionAndAnswer(obj);
      this.currentQuestionList = [...res.data];
      this.currentQuestionList.forEach((value, key, index) => {
        this.form1.answers.push(value);
      });
      // console.log(res);
    },

    // 获得问题数据
    getQuestionAll(val) {
      this.questionList = val;

      console.log(val);
    },

    openQuestion(val) {
      this.selectColumns = val;
      this.indexId = val.questionId;
      this.question = true;
    },

    // 修改数据
    saveQuestions(val) {
      this.question = false;
      this.questionList.forEach(x => {
        if (x.questionId == this.indexId) {
          // console.log(val,'val');
          // console.log(x,'x');
          x.questionContent = val.find(y => y.fieldName === 'QUESTION_CONTENT').initialValue;
          x.remark = val.find(y => y.fieldName === 'remark').initialValue;
          if (x.questionType == 80741001) {
            x.answer = val.find(y => y.fieldName === 'answer').initialValue;
          } else if (x.questionType == 80741002) {
            x.answer = val.find(y => y.fieldName === 'dynamicRadioSelect').initialValue;
          } else if (x.questionType == 80741003) {
            let list = val.find(y => y.fieldName === 'dynamicMultipleSelect').initialValue;
            let str = '';
            console.log(list, 'list');
            debugger;
            for (let i = 0; i < list.length; i++) {
              if (i === 0) {
                str = list[0];
              } else {
                str = str + ',' + list[i];
              }
            }
            // console.log(str, 'str');
            x.answer = str;
          }
        }
      });
      console.log(this.questionList, 'this.questionList');
    },

    closeQuestionModify(val) {
      this.question = val;
    }
  }
};
</script>

<style lang="less" scoped>
// .form-group {
//   margin-top: 10px;
//   span {
//     height: 50px;
//     line-height: 50px;
//     text-align: right;
//     width: 250px;
//     padding-left: 100px;
//   }
// }
</style>
